package com.xq.model.service.impl;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.google.gson.Gson;
import com.xq.config.properties.ManageProperties;
import com.xq.config.properties.MusicProperties;
import com.xq.model.dto.StationByRegionCodeDTO;
import com.xq.model.dto.StationByStationIdCDTO;
import com.xq.model.element.StationInfoEle;
import com.xq.model.entity.TBaseStationInfo;
import com.xq.model.mapper.TBaseStationInfoMapper;
import com.xq.model.service.ITBaseStationInfoService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xq.model.utils.ParentUtils;
import com.xq.utils.MapUtil;
import com.xq.utils.SignGenUtil;
import com.xq.utils.ClassUtil;
import com.xq.utils.HttpUtils;
import com.xq.utils.JsonUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;
import java.net.URISyntaxException;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 站点信息表 服务实现类
 * </p>
 *
 * @author xu
 * @since 2021-08-09
 */
@Service
public class TBaseStationInfoServiceImpl extends ServiceImpl<TBaseStationInfoMapper, TBaseStationInfo> implements ITBaseStationInfoService {
    @Resource
    private ParentUtils parentUtils;
    @Resource
    private MusicProperties musicProperties;
    @Resource
    private ManageProperties manageProperties;

    @Override
    public void addByStationIdC(List<String> stationIdCList) throws IllegalAccessException, IOException, URISyntaxException {
        StationByStationIdCDTO byStationIdCDTO = new StationByStationIdCDTO();
        // 初始化
        parentUtils.init(byStationIdCDTO,musicProperties);
        byStationIdCDTO.setInterfaceId("getStaInfoByStaId");
        byStationIdCDTO.setDataCode("STA_INFO_GLB");
        byStationIdCDTO.setElements(ClassUtil.objectToString(new StationInfoEle()));
        StringBuilder stringBuilder = new StringBuilder();
        // 对idc 封装
        stationIdCList.forEach(str ->{
            stringBuilder.append(",").append(str);
        });
        // 去除第一个 ,
        stringBuilder.delete(0,stringBuilder.indexOf(",")+1);
        byStationIdCDTO.setDataFormat("json");
        byStationIdCDTO.setStaIds(stringBuilder.toString());

        // 将对象转成map
        Map<String, String> signMap = MapUtil.beanToMap(byStationIdCDTO);
        // 获取签名
        String sign = SignGenUtil.getSign(signMap);

        byStationIdCDTO.setSign(sign);

        // 获取请求参数
        String params = MapUtil.toParamsFromMap(MapUtil.beanToMap(byStationIdCDTO));
        // 保存
        sendAndSave(params,"520100");
    }

    @Override
    public List<String> allStationIdC() {
        LambdaQueryWrapper<TBaseStationInfo> lqw = Wrappers.lambdaQuery();
        lqw.select(TBaseStationInfo::getStationIdC);
        List<TBaseStationInfo> list= list(lqw);
        return list.stream().map(TBaseStationInfo::getStationIdC).collect(Collectors.toList());
    }

    @Override
    public void postStation(String regionCode) throws IOException, URISyntaxException {
        LambdaQueryWrapper<TBaseStationInfo> lqw = Wrappers.lambdaQuery();
        lqw.eq(StrUtil.isNotBlank(regionCode), TBaseStationInfo::getParentCode, regionCode);
        List<TBaseStationInfo> list = list(lqw);

        if(list.size()>0){
            Gson gson = new Gson();
            String jsonStr = gson.toJson(list);
            HttpUtils.sendPostJson(manageProperties.getHost()+manageProperties.getStationPath(),jsonStr);
        }
    }

    @Override
    public boolean initStationByRegionCode(String regionCode) throws IOException, URISyntaxException, IllegalAccessException {
        StationByRegionCodeDTO stationDTO = new StationByRegionCodeDTO();
        // 初始化
        parentUtils.init(stationDTO,musicProperties);
        stationDTO.setInterfaceId("getStaInfoByRegionCode");
        stationDTO.setDataCode("STA_INFO_CHN");
        stationDTO.setElements(ClassUtil.objectToString(new StationInfoEle()));
        stationDTO.setAdminCodes(regionCode);
        // 暂不填乡镇编码
        //stationDTO.setTownCodes("");
        //暂时不排序
        //stationDTO.setOrderBy("Station_ID_C:ASC");
        // 暂时不限制
        //stationDTO.setLimitCnt("10");
        stationDTO.setDataFormat("json");

        // 将对象转成map
        Map<String, String> signMap = MapUtil.beanToMap(stationDTO);
        // 获取签名
        String sign = SignGenUtil.getSign(signMap);

        stationDTO.setSign(sign);

        // 获取请求参数
        String params = MapUtil.toParamsFromMap(MapUtil.beanToMap(stationDTO));

        return sendAndSave(params,regionCode);
    }

    private boolean sendAndSave(String params,String regionCode) throws IOException, URISyntaxException {
        // 获取返回数据 jsonArray
        JSONArray restArray = HttpUtils.sendGetToList(musicProperties, params);
        // 不为空继续操作
        assert restArray != null;
        // 转成list对象
        List<StationInfoEle> eleList = JsonUtils.jsonToList(restArray.toJSONString(),StationInfoEle.class);

        if(eleList==null || eleList.size() ==0){
            return true;
        }
        List<TBaseStationInfo> stationInfoList = new ArrayList<>();
        // 数据转换
        eleList.forEach(stationInfoEle -> {
            TBaseStationInfo stationInfo = new TBaseStationInfo();
            stationInfo.setCity(stationInfoEle.getCity());
            stationInfo.setStationLevel(stationInfoEle.getStation_levl());
            stationInfo.setVAcode4search(stationInfoEle.getV_ACODE_4SEARCH());
            stationInfo.setTown(stationInfoEle.getTown());
            stationInfo.setCountryCode(stationInfoEle.getCOUNTRYCODE());
            stationInfo.setProvince(stationInfoEle.getProvince());
            stationInfo.setStationName(stationInfoEle.getStation_Name());
            stationInfo.setRegionCode(stationInfoEle.getREGIONCODE());
            stationInfo.setNetCode(stationInfoEle.getNetCode());
            stationInfo.setAdminCodeChn(stationInfoEle.getAdmin_Code_CHN());
            stationInfo.setTownCode(stationInfoEle.getTown_code());
            stationInfo.setCountry(stationInfoEle.getCountry());
            stationInfo.setCnty(stationInfoEle.getCnty());
            stationInfo.setStationIdC(stationInfoEle.getStation_Id_C());
            stationInfo.setLat(stationInfoEle.getLat());
            stationInfo.setLon(stationInfoEle.getLon());
            stationInfo.setAlti(stationInfoEle.getAlti());
            stationInfo.setParentCode(regionCode);

            stationInfoList.add(stationInfo);
        });
        System.out.println("去重前:"+stationInfoList.size());
        // 根据stationIdC 去重
        List<TBaseStationInfo> distinctList = stationInfoList.stream()
                .collect(Collectors.collectingAndThen(Collectors.toCollection(()
                        -> new TreeSet<>(Comparator.comparing(TBaseStationInfo::getStationIdC))), ArrayList::new));
        System.out.println("去重后:"+distinctList.size());
        //保持至数据库
        return saveBatch(distinctList);
    }
}
